package Controller.Hadoop;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class hadoopConect {
	static String hostip = "192.168.42.146";
	static String username = "hadoop";
	static String identity = null;
	static String password = "hadoop";

	private static Session getSession() throws JSchException {

		JSch jsch = new JSch();
		if (identity != null) {
			jsch.addIdentity(identity);
		}
		Session session = jsch.getSession(username, hostip, 22);
		session.setConfig("StrictHostKeyChecking", "no");
		if (password != null) {
			session.setPassword(password);
		}
		return session;
	}

	public List<String> execs(String[] commands) {
		List<String> ret = new ArrayList<String>();
		try {
			Session session = getSession();
			session.connect();
			for (String command : commands) {
				ChannelExec channelExec = (ChannelExec) session
						.openChannel("exec");
				channelExec.setPty(true);
				channelExec.setCommand(command);
				InputStream inputStream = channelExec.getInputStream();
				channelExec.connect(30000);

				String output = "";

				byte[] buf = new byte[2048];
				int length;
				while ((length = inputStream.read(buf)) != -1) {
					String test = new String(buf, 0, length);
					output += new String(test.getBytes(), "UTF-8");
				}
				ret.add(StringUtils.chop(output));
				channelExec.disconnect();
			}
			session.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return ret;
	}

	public List<String> exec(String command) {
		List<String> ret = new ArrayList<String>();
		try {
			Session session = getSession();
			session.connect();

			ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
			channelExec.setPty(true);
			channelExec.setCommand(command);
			InputStream inputStream = channelExec.getInputStream();
			channelExec.connect(30000);

			String output = "";

			byte[] buf = new byte[2048];
			int length;
			while ((length = inputStream.read(buf)) != -1) {
				String test = new String(buf, 0, length);
				output = new String(test.getBytes(), "UTF-8");
				ret.add(StringUtils.chop(output));
			}
			
			channelExec.disconnect();

			session.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return ret;
	}
}
